package com.woniu.controller;


import com.woniu.entity.Result;
import com.woniu.pojo.Goods;
import com.woniu.pojo.Member;
import com.woniu.service.IGoodsService;
import com.woniu.vo.GoodsShoppingCartVo;
import com.woniu.vo.GoodsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: qiupeng
 * @Date: 2022/10/14
 * @Time: 16:24
 * @Version:
 */
@RestController
@RequestMapping("/springCat")
@Api(tags = "用户端商品购物车管理")
public class ShoppingCartController extends BaseController{

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IGoodsService goodsService;
/*    @Value(value = "0")
    private Integer goodsNum;*/


    @PostMapping("/addShppingCat")
    @ApiOperation("添加商品到购物车中")
    public Result searchGoods(@RequestBody GoodsShoppingCartVo goodsVo, HttpSession session) throws IllegalAccessException {
        Member member = (Member)session.getAttribute("member");
        String id = goodsVo.getGoodsId();
        Goods newGoods = goodsService.getById(id);

        Integer total = newGoods.getTotal();

        // 销量大于库存的的时候 库存显示不足
        if (total <= 0){
            return toDataResult(total,"库存不足");
        }
        return addShppingCat(goodsVo,member.getId());


    }

    @GetMapping("/addGoodsNum/{goodsId}")
    @ApiOperation("增加购物车的购买的数量")
    public Result addNum(@PathVariable String goodsId, HttpSession session) throws IllegalAccessException {
        Member member = (Member)session.getAttribute("member");
        // 定义每个用户购物车的key
        String shoppingCatKey = "SHOPPING_CART_KEY" + member.getId();
        String o =(String) stringRedisTemplate.opsForHash().get(shoppingCatKey, goodsId);
        System.out.println(o);
        Map<String, Object> value = getValue(o);
        System.out.println(value);
        String goodsNum1 = value.get("goodsNum").toString();
        Integer o1 =Integer.parseInt(goodsNum1) ;
        if (o1 >=4){
            return toDataResult("商品限购4件，请稍后再试");
        }
            value.put("goodsNum", o1 + 1);
        int goodsNum2 = Integer.parseInt(value.get("goodsNum").toString());
            stringRedisTemplate.opsForHash().put(shoppingCatKey,goodsId,value.toString());
        return toDataResult(goodsNum2);


    }
    @GetMapping("/reduceGoodsNum/{goodsId}")
    @ApiOperation("减少购物车的购买的数量")
    public Result reduceNum( @PathVariable String goodsId, HttpSession session) throws IllegalAccessException {
        Member member = (Member)session.getAttribute("member");
        // 定义每个用户购物车的key
        String shoppingCatKey = "SHOPPING_CART_KEY" + member.getId();
        String o =(String) stringRedisTemplate.opsForHash().get(shoppingCatKey, goodsId);
        System.out.println(o);
        Map<String, Object> value = getValue(o);

        String goodsNum1 = value.get("goodsNum").toString();
        Integer o1 =Integer.parseInt(goodsNum1) ;
        if (o1 <= 0){
            return toDataResult("商品个数不能为负数，请稍后再试");
        }
        value.put("goodsNum", o1 - 1);
        int goodsNum2 = Integer.parseInt(value.get("goodsNum").toString());
        stringRedisTemplate.opsForHash().put(shoppingCatKey,goodsId,value.toString());
        return toDataResult(goodsNum2);


    }

    public Result addShppingCat(GoodsShoppingCartVo goods,String memberId) throws IllegalAccessException {

        // 说明库存充足
        // 定义每个用户购物车的key
        String shoppingCatKey = "SHOPPING_CART_KEY" + memberId;
        // redis hash 的数据对象
        HashOperations<String, String, Object> hashOperations1 = stringRedisTemplate.opsForHash();
        HashOperations hashOperations = hashOperations1;
        // 判断一个商品是否添加到购物车当中
        System.err.println(goods.getGoodsId());
        boolean hashKey = hashOperations.getOperations().hasKey(shoppingCatKey);
        System.err.println(hashKey);

        if (hashKey){
            Map<String,Object> map = objectToMap(goods);
            hashOperations.put(shoppingCatKey, goods.getGoodsId(),map.toString());


        }else {



            Map<String,Object> map = objectToMap(goods);
            System.out.println(map);
            hashOperations.put(shoppingCatKey, goods.getGoodsId(),map.toString());

            // 如果不存在，就直接覆盖最新的数据进去&设置过期时间30天
            //设置 购物车时间
            Boolean expire = stringRedisTemplate.expire(shoppingCatKey, 30, TimeUnit.DAYS);
            if (expire){

            }
        }
        return toDataResult("添加购物车成功");

    }

    @PostMapping("/{goodsId}")
    @ApiOperation("删除购物车某个商品")
    public Result deleteShoppingCart(@PathVariable String goodsId,HttpSession session){
        Member member = (Member)session.getAttribute("member");
        // 存储购物车的key
        String shoppingCatKey = "SHOPPING_CART_KEY" + member.getId();
        // 将某个商品删除 在缓存当中
        stringRedisTemplate.opsForHash().delete(shoppingCatKey, goodsId);
        return success();
    }

    @GetMapping("/searchAllShoppingCart")
    @ApiOperation("查询购物车所有商品的数据信息")
    public Result searchAllShoppingCart(HttpSession session){
        Member member = (Member)session.getAttribute("member");
      //  存储购物车的key
        String shoppingCatKey = "SHOPPING_CART_KEY" + member.getId();
        // 从redis中获取购物车的数量
        Long size = stringRedisTemplate.opsForHash().size(shoppingCatKey);
        // 从redis获取购物车的所有的商品
        Map<String, String> entries = (Map)stringRedisTemplate.opsForHash().entries(shoppingCatKey);

        System.out.println(entries.toString());

        // 计算出总金额
        double totalMoney =0;
        List<Map<String,Object>>  resultList   = new ArrayList<>();
        // 将redis里面的数据全部循环出来
        for (Map.Entry<String, String> entry : entries.entrySet()){
            System.out.println(entry.toString() +":"+ entry.getKey());
            Map<String, Object> value = getValue(entry.getValue());
            resultList.add(value);

            Object price = value.get("price");
           // totalMoney += Integer.parseInt(String.valueOf(value.get("goodsNum")) * price
            double price1 =Double.parseDouble(String.valueOf(value.get("price"))) ;
            double goodsNum = (double)Integer.parseInt(String.valueOf(value.get("goodsNum")));
            totalMoney += price1 * goodsNum;

        };



        // 返回购物车的信息
        Map<String,Object> map = new HashMap<>();
        // 商品总价
        map.put("totalMoney",totalMoney);
        // 商品的个数
        map.put("totalCount",size);
        // 具体的商品所有的数据
        map.put("resultList",resultList);
        return toDataResult(map);

    }


    /**
     * 对象转Map
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public  Map objectToMap(Object object) throws IllegalAccessException {
        Map<String, Object> map = new HashMap();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(object));
        }
        return map;
    }

    /**
     *  string转map
     * @param param
     * @return
     */
    public  Map<String, Object> getValue(String param) {
        Map<String, Object> map = new HashMap<>();
        String str = "";
        String key = "";
        Object value = "";
        char[] charList = param.toCharArray();
        boolean valueBegin = false;
        for (int i = 0; i < charList.length; i++) {
            char c = charList[i];
            if (c == '{') {
                if (valueBegin == true) {
                    value = getValue(param.substring(i, param.length()));
                    i = param.indexOf('}', i) + 1;
                    map.put(key, value);
                }
            } else if (c == '=') {
                valueBegin = true;
                key = str;
                str = "";
            } else if (c == ',') {
                valueBegin = false;
                value = str;
                str = "";
                map.put(key, value);
            } else if (c == '}') {
                if (str != "") {
                    value = str;
                }
                map.put(key, value);
                return map;
            } else if (c != ' ') {
                str += c;
            }
        }
        return map;
    }

    /**
     * 实现命令：HGET key field，返回哈希表 key中给定域 field的值
     *
     * @param key
     * @param field
     * @return
     */
    public String hget(String key, String field) {
        return (String) stringRedisTemplate.opsForHash().get(key, field);
    }

    /**
     * 向一张hash表中放入数据,如果存在就覆盖原来的值。
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            stringRedisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
